﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace cjwygl
{
    public partial class FrmSinglefeeUpdate2 : Form
    {
        private int updateId = -1;
        private String sAddCustomer = "";

        public FrmSinglefeeUpdate2()
        {
            InitializeComponent();
            InitializeCompanies();
            InitializeMonths();
            button_add.Text = "添加并关闭";
            button_add.Enabled = true;
            button_continue.Enabled = true;
            this.Text = "单项费用录入-添加一条记录";
        }

        public FrmSinglefeeUpdate2(String customer, String genMonth)
        {
            InitializeComponent();
            InitializeCompanies();
            InitializeMonths();
            button_add.Text = "添加并关闭";
            button_add.Enabled = true;
            button_continue.Enabled = true;
            this.Text = "单项费用录入-添加一条记录";
            sAddCustomer = customer;

            if (genMonth != "")
            {
                comboBox_genMonth.SelectedItem = genMonth;
            }
        }

        public FrmSinglefeeUpdate2(int id)
        {
            InitializeComponent();
            updateId = id;
            button_add.Text = "修改";
            button_add.Enabled = true;
            button_continue.Enabled = false;
            this.Text = "单项费用录入-修改记录" + updateId;
            comboBox_companyname.Enabled = false;
            comboBox_genMonth.Enabled = false;
            comboBox_type.Enabled = false;
        }

        public void InitializeMonths()
        {
            using (DataBase db = new DataBase())
            {
                string sql = "SELECT DISTINCT GEN_MONTH FROM CJ_MAIN_FEE order by GEN_MONTH";
                DataTable dt = db.ExecuteDataTable(sql);
                foreach (DataRow dr in dt.Rows)
                {
                    comboBox_genMonth.Items.Add(dr[0].ToString());
                }
            }
        }

        public void InitializeCompanies()
        {
            List<ComboItem> companies = new List<ComboItem>();
            companies.Add(new ComboItem { Text = "", Value = "0" });
            using (DataBase db = new DataBase())
            {
                string sql = "SELECT ID,COMPANY_NAME FROM CJ_CUSTOMER_INFO order by COMPANY_NAME";
                DataTable dt = db.ExecuteDataTable(sql);
                foreach (DataRow dr in dt.Rows)
                {
                    companies.Add(new ComboItem
                    {
                        Text = dr[1].ToString(),
                        Value = dr[0].ToString()
                    });

                }
            }
            comboBox_companyname.DisplayMember = "Text";
            comboBox_companyname.ValueMember = "Value";
            comboBox_companyname.DataSource = companies;

        }

        private void FrmSinglefeeUpdate2_Load(object sender, EventArgs e)
        {
            if (updateId > 0)
            {
                using (DataBase db = new DataBase())
                {
                    string sql = "SELECT * FROM [View_MAIN_FEE] WHERE [ID]=" + updateId;
                    DataTable dt = db.ExecuteDataTable(sql);
                    if (dt.Rows.Count == 1)
                    {
                        DataRow dr = dt.Rows[0];
                        String company_name = dr["COMPANY_NAME"].ToString();
                        comboBox_companyname.Items.Add(company_name);
                        comboBox_companyname.SelectedIndex = 0;

                        String fee_type = dr["FEE_TYPE"].ToString();
                        comboBox_type.SelectedItem = fee_type;

                        comboBox_genMonth.Text = dr["GEN_MONTH"].ToString();

                        if (fee_type == "水费" || fee_type == "电费")
                        {
                            dateTimePicker_cbtime.Value = (DateTime)dr["LAST_END"];
                        }
                        else
                        {
                            dateTimePicker_cur.Value = (DateTime)dr["LAST_END"];
                            dateTimePicker_next.Value = (DateTime)dr["NEXT_START"];
                        }

                        textBox_fee.Text = dr["FEE"].ToString();
                        textBox_comment.Text = dr["COMMENT"].ToString();

                        label_paid.Visible = (bool)dr["IS_PAID"];
                    }
                }
            }
            else
            {
                if (sAddCustomer != "")
                {
                    foreach (object item in comboBox_companyname.Items)
                    {
                        if (((ComboItem)item).Text == sAddCustomer)
                        {
                            comboBox_companyname.SelectedItem = item;
                            break;
                        }
                    }
                }
            }

        }

        private int AddNewRecord()
        {
            //Check integrity
            if (comboBox_companyname.Text == "" ||
                comboBox_type.Text == "" ||
                comboBox_genMonth.Text == "")
            {
                MessageBox.Show("请指定公司名、名目和费用年月!");
                return 0;
            }

            String genMonth = comboBox_genMonth.Text;
            if (genMonth.Length != 6)
            {
                MessageBox.Show("费用年月格式不正确!");
                return 0;
            }

            int month = 0;
            int.TryParse(genMonth.Substring(4), out month);
            if (month < 1 || month > 12)
            {
                MessageBox.Show("费用年月格式不正确!");
                return 0;
            }
            int year = 0;
            int.TryParse(genMonth.Substring(0, 4), out year);
            if (year.ToString() != genMonth.Substring(0, 4))
            {
                MessageBox.Show("费用年月格式不正确!");
                return 0;
            }

            string company_id = comboBox_companyname.SelectedValue.ToString();
            string fee_type = comboBox_type.Text;
            // 检查单项费用记录是否已存在
            using (DataBase db = new DataBase())
            {
                db.AddParameter("COMPANY_ID", company_id);
                db.AddParameter("GEN_MONTH", genMonth);
                db.AddParameter("FEE_TYPE", fee_type);
                DataTable dtMainFee = db.ExecuteDataTable("SELECT TOP 1 * FROM CJ_MAIN_FEE WHERE COMPANY_ID=@COMPANY_ID AND GEN_MONTH=@GEN_MONTH AND FEE_TYPE=@FEE_TYPE");
                if (dtMainFee.Rows.Count != 0)
                {
                    MessageBox.Show("指定的单项费用记录已经存在!");
                    return 0;
                }
            }

            if (fee_type != "房租")
            {
                // 检查对应的“房租”记录是否已添加
                using (DataBase db = new DataBase())
                {
                    db.AddParameter("COMPANY_ID", company_id);
                    db.AddParameter("GEN_MONTH", genMonth);
                    DataTable dtMainFee = db.ExecuteDataTable("SELECT TOP 1 * FROM CJ_MAIN_FEE WHERE COMPANY_ID=@COMPANY_ID AND GEN_MONTH=@GEN_MONTH AND FEE_TYPE='房租'");
                    if (dtMainFee.Rows.Count == 0)
                    {
                        MessageBox.Show("必须先为该公司在 " + genMonth + " 月上添加“房租”费用记录!");
                        return 0;
                    }
                }
            }

            double dFee = 0.0;
            if (!double.TryParse(textBox_fee.Text, out dFee))
            {
                MessageBox.Show("请输入正确的金额数值");
                textBox_fee.Focus();
                return 0;
            }

            if (fee_type != "水费" && fee_type != "电费")
            {
                if (dateTimePicker_cur.Value >= dateTimePicker_next.Value)
                {
                    MessageBox.Show("结算日期设置不正确!");
                    return 0;
                }
            }


            using (DataBase db = new DataBase())
            {
                db.AddParameter("COMPANY_ID", company_id);
                db.AddParameter("GEN_MONTH", genMonth);
                db.AddParameter("FEE_TYPE", fee_type);
                db.AddParameter("FEE", dFee);
                if (comboBox_type.Text == "水费" ||
                    comboBox_type.Text == "电费")
                {
                    db.AddParameter("LAST_END", dateTimePicker_cbtime.Value);
                    db.AddParameter("NEXT_START", DBNull.Value);
                }
                else
                {
                    db.AddParameter("LAST_END", dateTimePicker_cur.Value);
                    db.AddParameter("NEXT_START", dateTimePicker_next.Value);
                }
                db.AddParameter("COMMENT", textBox_comment.Text);
                db.AddParameter("OP_NAME", userinfo.username);
                db.AddParameter("OP_ID", userinfo.id);
                db.AddParameter("LOG_TIME", DateTime.Now);
                db.AddParameter("LAST_MODIFY_DATE", DateTime.Now);

                db.AddParameter("MODIFY_COMMENT", DateTime.Now.ToString() + ":" + userinfo.username + "创建了该条记录;");

                String sql = "INSERT INTO [CJ_MAIN_FEE]([FEE_TYPE],[FEE],[LAST_END],[NEXT_START],[COMMENT],[OP_NAME]" +
                ",[OP_ID],[LOG_TIME],[LAST_MODIFY_DATE],[MODIFY_COMMENT],[COMPANY_ID],[IS_PAID],[GEN_MONTH])" +
                "VALUES (@FEE_TYPE,@FEE,@LAST_END,@NEXT_START,@COMMENT,@OP_NAME,@OP_ID,@LOG_TIME" +
                ",@LAST_MODIFY_DATE,@MODIFY_COMMENT,@COMPANY_ID,0,@GEN_MONTH)";

                return db.ExecuteNonQuery(sql);

            }
        }

        private int ModifyRecord(int id)
        {
            //Check integrity
            if (comboBox_companyname.Text == "" ||
                comboBox_type.Text == "" ||
                comboBox_genMonth.Text == "")
            {
                MessageBox.Show("请指定公司名、名目和费用年月!");
                return 0;
            }

            double dFee = 0.0;
            if (!double.TryParse(textBox_fee.Text, out dFee))
            {
                MessageBox.Show("请输入正确的金额数值");
                textBox_fee.Focus();
                return 0;
            }

            if (comboBox_type.Text != "水费" && comboBox_type.Text != "电费")
            {
                if (dateTimePicker_cur.Value >= dateTimePicker_next.Value)
                {
                    MessageBox.Show("结算日期设置不正确!");
                    return 0;
                }
            }

            using (DataBase db = new DataBase())
            {
                db.AddParameter("ID", id);
                db.AddParameter("FEE", dFee);
                if (comboBox_type.Text == "水费" ||
                    comboBox_type.Text == "电费")
                {
                    db.AddParameter("LAST_END", dateTimePicker_cbtime.Value);
                    db.AddParameter("NEXT_START", DBNull.Value);
                }
                else
                {
                    db.AddParameter("LAST_END", dateTimePicker_cur.Value);
                    db.AddParameter("NEXT_START", dateTimePicker_next.Value);
                }
                db.AddParameter("COMMENT", textBox_comment.Text);
                db.AddParameter("OP_NAME", userinfo.username);
                db.AddParameter("OP_ID", userinfo.id);
                db.AddParameter("LAST_MODIFY_DATE", DateTime.Now);
                db.AddParameter("MODIFY_COMMENT", DateTime.Now.ToString() + ":" + userinfo.username + "修改了该条记录;");

                return db.ExecuteNonQuery("UPDATE CJ_MAIN_FEE SET FEE=@FEE,LAST_END=@LAST_END,NEXT_START=@NEXT_START,COMMENT=@COMMENT,OP_NAME=@OP_NAME,OP_ID=@OP_ID,LAST_MODIFY_DATE=@LAST_MODIFY_DATE,MODIFY_COMMENT=MODIFY_COMMENT+@MODIFY_COMMENT WHERE ID=@ID");

            }
        }

        private void button_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void ClearAll()
        {
            comboBox_companyname.SelectedIndex = -1;
            comboBox_type.SelectedIndex = -1;
            comboBox_genMonth.Text = "";
            textBox_fee.Text = "";
            textBox_comment.Text = "";
            dateTimePicker_cbtime.Value = DateTime.Now;
            dateTimePicker_cur.Value = DateTime.Now;
            dateTimePicker_next.Value = DateTime.Now.AddMonths(1);
        }

        private void button_continue_Click(object sender, EventArgs e)
        {
            if (updateId < 0)
            {
                if (AddNewRecord() == 1)
                {
                    MessageBox.Show("添加成功");
                    ClearAll();
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
        }

        private void button_add_Click(object sender, EventArgs e)
        {
            if (updateId > 0)
            {
                if (ModifyRecord(updateId) == 1)
                {
                    MessageBox.Show("修改成功");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("修改失败");
                }
            }
            else
            {
                if (AddNewRecord() == 1)
                {
                    MessageBox.Show("添加成功");
                    this.Close();
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
        }

        private void comboBox_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_type.SelectedItem == null)
                return;

            if (comboBox_type.Text == "水费"
                || comboBox_type.Text == "电费")
            {
                label_cbtime.Enabled = true;
                dateTimePicker_cbtime.Enabled = true;
                label_prev.Enabled = false;
                label_cur.Enabled = false;
                dateTimePicker_cur.Enabled = false;
                label_cur_to.Enabled = false;
                label_next.Enabled = false;
                dateTimePicker_next.Enabled = false;
            }
            else
            {
                label_cbtime.Enabled = false;
                dateTimePicker_cbtime.Enabled = false;
                label_prev.Enabled = true;
                label_cur.Enabled = true;
                dateTimePicker_cur.Enabled = true;
                label_cur_to.Enabled = true;
                label_next.Enabled = true;
                dateTimePicker_next.Enabled = true;
            }
        }

        private void dateTimePicker_cur_ValueChanged(object sender, EventArgs e)
        {
            label_prev.Text = "上期结止日期： " + dateTimePicker_cur.Value.AddDays(-1).ToString("yyyy年MM月dd日");
        }

        private void dateTimePicker_next_ValueChanged(object sender, EventArgs e)
        {
            label_cur_to.Text = "- " + dateTimePicker_next.Value.AddDays(-1).ToString("yyyy年MM月dd日");
        }
    }
}
